<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col>
      <!--拓扑图数据-->
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="80px" v-show="showSearch" >
        <el-form-item label="名称" prop="topoName">
          <el-input v-model="queryParams.topoName" placeholder="请输入名称" size="small" clearable style="width: 150px"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="queryParams.remark" placeholder="请输入备注" size="small" clearable style="width: 150px"/>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker @change="handleQuery" v-model="dateRange" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"/>
        </el-form-item>

        <el-form-item>
          <el-button type="primary"  size="mini" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery('queryForm')">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary"  v-hasPermi="['saveTopoTopology']"  icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" v-hasPermi="['updateTopoTopology']"  icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" v-hasPermi="['deleteTopoTopology']"  icon="el-icon-delete" size="mini" :disabled="single" @click="handleDelete">删除</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="queryTopoTopologyPageResList" :columns="columns"></right-toolbar>
      </el-row>

        <el-table ref="multipleTable" :stripe="true" v-loading="loading" :data="dataList" @selection-change="handleSelectionChange"
                  @sort-change='tableSortChange' :default-sort="{prop: 'sort', order: 'descending'}">
          <el-table-column type="selection" align="center"/>
          <el-table-column label="名称" align="left" prop="topoName"  width="300"/>
          <el-table-column label="封面" align="center" prop="coverImg" width="200">
            <template slot-scope="scope">
              <img @click="handlePreviewTopology(scope.row)" width="100" height="100" :src="scope.row.coverImg" :onerror="$store.state.defaultAvatar"/>
            </template>
          </el-table-column>
          <el-table-column label="创建部门" align="left" prop="createDeptName"  width="250" />
          <el-table-column label="更新时间" align="left" prop="updateTime" sortable='custom' width="200" />
          <el-table-column label="备注" sortable='custom' align="center" prop="remark"/>
          <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" v-hasPermi="['updateTopoTopology']" icon="el-icon-setting"  @click="handleDesignTopology(scope.row)">设计</el-button>
              <el-button size="mini" type="text" icon="el-icon-view"  @click="handlePreviewTopology(scope.row)">预览</el-button>
              <!--  <el-button size="mini" type="text" v-hasPermi="['updateTopoTopology']" icon="el-icon-edit"  @click="handleUpdate(scope.row)">修改</el-button>
                    <el-button size="mini" type="text" v-hasPermi="['deleteTopoTopology']" icon="el-icon-delete"  @click="handleDelete(scope.row)">删除</el-button>-->
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total>0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.rows"
                    @pagination="queryTopoTopologyPageResList"/>
      </el-col>
    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="addUpdateOpen" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="addUpdateOpenRules"  label-width="80px">
        <el-form-item label="名称" prop="topoName">
          <el-input :hide-required-asterisk="true" autocomplete="off" v-model="form.topoName" placeholder="请输入名称" maxlength="20" />
        </el-form-item>

        <el-form-item label="封面" prop="coverImg" ref="coverImg">
          <el-upload
            ref="image"
            class="avatar-uploader"
            action="#"
            :auto-upload="false"
            accept="image/jpeg,image/gif,image/png,image/jpg"
            :on-change="requestUpload"
            :show-file-list="false">
          <img v-if="form.coverImg" :src="form.coverImg"  class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>


        <el-form-item label="备注" prop="remark">
          <el-input :hide-required-asterisk="true" autocomplete="off" v-model="form.remark" placeholder="请输入备注" maxlength="100" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelAddUpdateOpen">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {queryTopoTopologyPageResList, saveTopoTopology, updateTopoTopology, deleteTopoTopologyByTopoId} from '@/api/topo/topology'
  //默认查询参数
  let defaultQueryParams = {
    topoName: undefined,
    startTime: undefined,
    endTime: undefined,
    remark: undefined,
    page: 1,
    rows: 10
  }
  export default {
    name: "topologyAdmin",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 显示搜索条件
        showSearch: true,
        // table表格数据
        dataList: [],
        // 日期范围
        dateRange: [],
        // 弹出层标题
        title: "",
        // 是否显示新增修改弹出层
        addUpdateOpen: false,
        // 增加修改表单参数
        form: {},
        // 查询参数
        queryParams: { ...defaultQueryParams },
        //列信息
        columns: [],
        // 新增修改表单校验
        addUpdateOpenRules: {
          topoName: [
            { required: true, message: "名称必须填写",trigger: "blur" },
          ],
          coverImg: [
            { required: true, message: "封面必须上传"},
          ]
        }
      }
    },
    created() {
      this.queryTopoTopologyPageResList();
    },
    methods: {
      /** 查询拓扑图列表 */
      queryTopoTopologyPageResList() {
        this.loading = true
        queryTopoTopologyPageResList(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.dataList = response.data.records
          this.total = response.data.total
          this.loading = false
        })
      },

      //上传图元图标
      requestUpload(file) {
        let that = this
        const typeArr = ['image/png', 'image/gif', 'image/jpeg', 'image/jpg'];
        const isJPG = typeArr.indexOf(file.raw.type) !== -1;
        if (!isJPG) {
          this.$message.error('只能是图片!');
          return;
        }
        const isLt1M = file.size / 1024 / 1024 < 1;
        if (!isLt1M) {
          this.$message.error('上传封面图片大小不能超过 1M!');
          return
        }
        let reader = new FileReader();
        reader.readAsDataURL(file.raw);
        reader.onload = function(e){
          that.form = {
            ...that.form,
            coverImg: this.result
          }
          that.$refs["coverImg"].clearValidate()
        }
      },

      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.topoId)
        this.single = selection.length !== 1;
        this.multiple = !selection.length
      },
      //排序
      tableSortChange(column){
        //格式化排序参数，构建中
        this.orderByFormat(this.queryParams,column);
        //执行查询方法
        this.queryTopoTopologyPageResList()
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.addUpdateOpen = true;
        this.title = "添加拓扑图";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        row = row.isTrusted ? this.$refs.multipleTable.selection[0] : row;
        //修改表单填充
        this.form = {...row};
        this.addUpdateOpen = true;
        this.title = "修改拓扑图";
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        row = row.isTrusted ? this.$refs.multipleTable.selection[0] : row;
        this.$confirm('是否确认删除所选拓扑图?', "警告", {
          cancelButtonText: "取消",
          confirmButtonText: "确定",
          type: "warning"
        }).then(function() {
          const topoId={topoId:row.topoId}
          return deleteTopoTopologyByTopoId(topoId);
        }).then(response => {
          this.$modal.msgSuccess(response.message)
          this.queryTopoTopologyPageResList();
        }).catch(function() {});
      },
      /** 跳转到设计界面 */
      handleDesignTopology(row) {
        let url = window.location.protocol + '//' + window.location.host
        let topoEditUrl = `${url}/plugin/topo/edit.html?topo=${row.topoId}&timestamp=`+new Date().getTime()
        window.open(topoEditUrl, '_blank');
      },
      /** 跳转到预览界面 */
      handlePreviewTopology(row) {
        let url = window.location.protocol + '//' + window.location.host
        let topoEditUrl = `${url}/plugin/topo/preview.html?topo=${row.topoId}&timestamp=`+new Date().getTime()
        window.open(topoEditUrl, '_blank');
      },

      /** 提交保存或修改按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.topoId !== undefined) {
              updateTopoTopology(this.form).then(response => {
                this.$modal.msgSuccess(response.message)
                this.queryTopoTopologyPageResList();
                this.addUpdateOpen = false
              });
            } else {
              saveTopoTopology(this.form).then(response => {
                this.$modal.msgSuccess(response.message)
                this.queryTopoTopologyPageResList();
                this.addUpdateOpen = false
              });
            }
          }
        });
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.page = 1
        this.queryTopoTopologyPageResList()
      },
      /** 重置按钮操作 */
      resetQuery(fromId) {
        this.dateRange = [];
        this.resetForm(fromId);
        this.handleQuery()
      },
      // 取消修改增加弹出层按钮
      cancelAddUpdateOpen() {
        this.addUpdateOpen = false
      },
      // 表单重置
      reset() {
        this.form = {
          topoId: undefined,
          topoName: undefined,
          remark: undefined
        };
        this.resetForm('form')
      }
    }
  }
</script>
<style lang="less" scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    border: 1px dashed #d9d9d9;
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .avatar {
    width: 100px;
    height: 100px;
    line-height: 100px;
    display: block;
  }
</style>
